package com.core.ui.customtag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.core.protocols.ICustomDatasourceDelegate;
import com.core.protocols.ITabSheetDatasource;
import com.core.ui.customcell.TabSheetItemCell;

public class TabSheetView
        extends TagSupport
        implements ICustomDatasourceDelegate {

	private static final long   serialVersionUID = 1L;

	private ITabSheetDatasource datasource;



	public ITabSheetDatasource getDatasource () {

		return datasource;
	}



	public void setDatasource ( ITabSheetDatasource datasource ) {

		this.datasource = datasource;
		if ( this.datasource != null ) {
			this.datasource.setCustomDatasourceDelegate(this);
		}
	}



	public void release () {

		super.release();
		datasource = null;
	}



	public TabSheetView() {

		datasource = null;
	}



	public int doStartTag ()
	        throws JspException {

		if ( datasource == null ) {
			return SKIP_BODY;
		}

		datasource.reloadData();

		return SKIP_BODY;
	}



	@Override
	public void refreshContent () {

		String tabsPanelStyleClassName = datasource.tabsPanelStyleClassName();

		StringBuilder sb = new StringBuilder();
		sb.append(String.format("<div class=\"%s\">", tabsPanelStyleClassName));

		int itemsCount = datasource.tabSheetCellsCount();
		for ( int i = 0; i < itemsCount; i++ ) {
			TabSheetItemCell item = datasource.tabSheetCellAtIndex(i);
			if ( item == null ) {
				continue;
			}
			sb.append(item.toString());
		}

		sb.append("</div>");

		try {
			JspWriter writer = pageContext.getOut();
			writer.append(sb.toString());
		} catch ( IOException e ) {
		}

	}

}
